package io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * @author Cheng Jun
 * @version 1.0
 * Description:
 * @date 2019/10/23 16:36
 */
public class IOExceptionExample {
    public static void main(String[] args) {
        //从 Java 7 开始，我们可以使用名为 try-with-resources 的构造，
        //当try块完成时，FileInputStream 将自动关闭，换句话说，只要线程已经执行出try代码块，fileInputStream 就会被关闭。
        try (FileInputStream fileInputStream = new FileInputStream(".\\src\\io\\TestFile\\ForByte.txt")) {
            int data = fileInputStream.read();
            while (data != -1) {
                System.out.print((char) data);
                data = fileInputStream.read();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            logIOException(ex);
        }

    }

    /**
     * 将异常输出到：.\src\io\TestFile\ForIOExceptionExample.txt 文件中
     *
     * @param ex
     */
    public static void logIOException(IOException ex) {
        String fileName = ".\\src\\io\\TestFile\\ForIOExceptionExample.txt";
        File forIOExceptionExample = new File(fileName);
        if (!forIOExceptionExample.exists()) {
            try {
                forIOExceptionExample.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(fileName + "创建失败");
            }
        }

        try (PrintStream printStream = new PrintStream(fileName)) {
            ex.printStackTrace(printStream);
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

}
